package io.github.talelin.latticy.common.configuration;

import com.alibaba.fastjson.JSONObject;
import io.github.talelin.latticy.model.RulesDO;
import io.github.talelin.latticy.service.RulesService;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @authoer:wulongbo
 * @createDate:2022/8/8
 * @description:
 */
@Configuration
@Slf4j
public class KieConfig {
    @Autowired
    RulesService rulesService;

    @Autowired
    FreeMarkerConfig freeMarkerConfig;

    protected KieFileSystem kieFileSystem() {
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        List<RulesDO> all = rulesService.getAllRules();
        all.forEach(a -> {
            //该目录文件为虚拟目录,不需要实际存在,**后缀一定要带.drl**
            String path="src/main/resources/rules/" + a.getId() + ".drl";
            kieFileSystem.write(path, a.getRule().getBytes());
        });
        return kieFileSystem;
    }

    public KieContainer kieContainer() {
        final KieRepository kieRepository = getKieServices().getRepository();
        kieRepository.addKieModule(() -> kieRepository.getDefaultReleaseId());
        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }
}
